from datetime import timedelta
import os
import openpyxl
import requests  ###


def check_missing_days_main(conn, repo_str, branch_list, start_date, end_date):
    repos = [r.strip() for r in repo_str.split(',')]
    branches = branch_list

    all_dates = {start_date + timedelta(days=i) for i in range((end_date - start_date).days + 1)}
    missing_total = 0

    for repo in repos:
        for branch in branches:
            logged_dates = get_logged_dates(conn, repo, branch, start_date, end_date)
            missing_dates = sorted(all_dates - logged_dates)

            if missing_dates:
                print(f"❗ {repo} / {branch} — {len(missing_dates)} missing")
                for d in missing_dates:
                    print(" ", generate_command(d.isoformat(), repo, branch))
                missing_total += len(missing_dates)
            else:
                print(f"✅ {repo} / {branch} — OK")

    if missing_total == 0:
        print("✅ No missing dates found.")
    else:
        print(f"⚠️ Found {missing_total} missed runs. see commands above.")

def get_logged_dates(connection, repo, branch, start_date, end_date):
    sql = """
        SELECT DISTINCT date_param
        FROM gitee_logs
        WHERE repo = %s AND branch = %s AND date_param BETWEEN %s AND %s
    """
    with connection.cursor() as cursor:
        cursor.execute(sql, (repo, branch, start_date, end_date))
        rows = cursor.fetchall()
        return {row[0] for row in rows}

def generate_command(date_str, repo, branch):
    return f"python3 gitee_review.py -d {date_str} -p {repo} -b {branch}"

def dump_all_prs_to_excel(conn, file_name, date_since=None, date_until=None):
    base_sql = """
        SELECT ID, Name, Login, PR_Name, PR_URL, PR_State,
               PR_Created_Date, PR_Merged_Date, Branch, Repo,
               Additions, Deletions, Reviewers
        FROM pull_requests
    """
    where_clauses = []
    params = []

    if date_since and date_until:
        where_clauses.append("PR_Created_Date BETWEEN %s AND %s")
        params.extend([date_since, date_until])
    elif date_since:
        where_clauses.append("PR_Created_Date >= %s")
        params.append(date_since)
    elif date_until:
        where_clauses.append("PR_Created_Date <= %s")
        params.append(date_until)

    if where_clauses:
        base_sql += " WHERE " + " AND ".join(where_clauses)

    wb = openpyxl.Workbook()
    ws = wb.active
    headers = ["PR ID", "Name", "Login", "PR_Name", "PR_URL", "PR_State",
               "PR_Created_Date", "PR_Merged_Date", "branch", "Repo",
               "Additions", "Deletions", "Reviewers"]
    ws.append(headers)

    with conn.cursor() as cursor:
        cursor.execute(base_sql, tuple(params))
        for row in cursor.fetchall():
            ws.append(row)

    wb.save(file_name)
    print(f"✅ All PRs exported to {file_name}")
    return file_name


def upload_to_nexus(file_path, nexus_url, repository, username, password, repository_path=None):
    """
    Загружает файл на Nexus (RAW hosted repo).

    nexus_url        — базовый URL Nexus, например: http://nexus.local:8081
    repository       — имя репозитория в Nexus
    repository_path  — путь внутри репозитория (может быть пустым)
    """
    file_name = os.path.basename(file_path)

    if repository_path:
        upload_url = f"{nexus_url}/repository/{repository}/{repository_path}/{file_name}"
    else:
        upload_url = f"{nexus_url}/repository/{repository}/{file_name}"

    with open(file_path, 'rb') as f:
        response = requests.put(upload_url, data=f, auth=(username, password))

    if response.status_code in (200, 201):
        print(f"✅ File {file_name} successfully uploaded to {upload_url}")
    else:
        raise Exception(f"❌ Upload failed: {response.status_code} {response.text}")